package com.ciwong.epaper.modules.epaper.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.modules.epaper.bean.EpaperInfo;
import com.ciwong.epaper.modules.evaluate.bean.UserDkWork;
import com.ciwong.epaper.modules.me.adapter.HomeWorkAdapter;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.widget.DKWorkDialog;
import com.ciwong.epaper.widget.HomeWorkHintDialog;
import com.ciwong.libs.utils.CWLog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class UserDKListAdapter extends BaseExpandableListAdapter {
    /**
     * 添加类型：全部
     */
    public static final int ADD_TYPE_ALL = 0;

    /**
     * 添加类型：已添加
     */
    public static final int ADD_TYPE_YES = 1;

    /**
     * 添加类型：未添加
     */
    public static final int ADD_TYPE_NO = 2;

    /**
     * 添加类型
     */
    private int addType;

    private String[] cheStr = {"一", "二", "三", "四", "五", "六", "七"};
    private String[] numberStr = {"1", "2", "3", "4", "5", "6", "7"};


    /**
     * 上下文
     */
    private Context mContext;

    private List<UserDkWork> userDkWorks;

    public List<UserDkWork> getUserDkWorks() {
        return userDkWorks;
    }

    public UserDKListAdapter(Context context, List<UserDkWork> userDkWorks, int addType) {
        this.mContext = context;
        this.userDkWorks = userDkWorks;
        this.addType = addType;
    }

    @Override
    public int getGroupCount() {
        return userDkWorks == null ? 0 : userDkWorks.size();
    }

    @Override
    public int getChildrenCount(int i) {
        return 1;
    }

    @Override
    public Object getGroup(int i) {
        return userDkWorks == null ? 0 : userDkWorks.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return userDkWorks == null ? 0 : userDkWorks.get(i);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(int i, boolean b, View view, ViewGroup viewGroup) {
        GroupViewHolder groupViewHolder = null;
        if (view == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.activity_user_dk_list_parent, null);
            groupViewHolder = new GroupViewHolder();
            groupViewHolder.item_my_group_parent_view = view.findViewById(R.id.dk_my_group_parent_view);
            groupViewHolder.iv_my_work_status_start = view.findViewById(R.id.iv_my_work_status_start);
            groupViewHolder.iv_my_work_status_finish = view.findViewById(R.id.iv_my_work_status_finish);
            groupViewHolder.mTimeTv = view.findViewById(R.id.dk_my_group_time_tv);
            groupViewHolder.iv_my_group_msg = view.findViewById(R.id.dk_my_group_msg);
            view.setTag(groupViewHolder);
        } else {
            groupViewHolder = (GroupViewHolder) view.getTag();
        }
        setGroupView(i, groupViewHolder);
        return view;
    }

    /**
     * 设置父标题
     *
     * @param groupPosition
     * @param groupViewHolder
     */
    private void setGroupView(final int groupPosition, final GroupViewHolder groupViewHolder) {
        if (null != userDkWorks) {
            UserDkWork userDkWork = userDkWorks.get(groupPosition);
            SimpleDateFormat formatter2 = new SimpleDateFormat("HH:mm");
            long effdate = userDkWork.getEffectiveDate();
            long data5 = effdate * 1000;
            final String mountAndDay = CWUtils.formatDate5two(data5);
            final String time = formatter2.format(data5);
            String endWeekDate = CWUtils.formatDateToWeek2(data5);
            final String endTime = mContext.getResources().getString(R.string.str_dead_line) + "  " + mountAndDay + " (" + endWeekDate + ") " + time;

            if (userDkWork.getEffectiveDate() > userDkWork.getNowDate()) {
                //打卡作业未结束
                groupViewHolder.iv_my_work_status_start.setVisibility(View.VISIBLE);
                groupViewHolder.iv_my_work_status_finish.setVisibility(View.GONE);
                final String workTime = CWUtils.getWorkStopTime(userDkWork.getEffectiveDate() - userDkWork.getNowDate());
                groupViewHolder.mTimeTv.setText("进行中-" + workTime + "后截止");
                groupViewHolder.mTimeTv.setTextColor(mContext.getResources().getColor(R.color.color_light_green));
                groupViewHolder.item_my_group_parent_view.setBackgroundColor(mContext.getResources().getColor(R.color.work_status_start));
            } else {
                //打卡作业已经结束
                groupViewHolder.iv_my_work_status_start.setVisibility(View.GONE);
                groupViewHolder.iv_my_work_status_finish.setVisibility(View.VISIBLE);
                final String workTime = CWUtils.getWorkFinishTime(userDkWork.getEffectiveDate());
                groupViewHolder.mTimeTv.setText("已结束-" + workTime + "截止");
                groupViewHolder.mTimeTv.setTextColor(mContext.getResources().getColor(R.color.black));
                groupViewHolder.item_my_group_parent_view.setBackgroundColor(mContext.getResources().getColor(R.color.ls_item_option_selected));
            }

            final GroupViewHolder finalGroupViewHolder = groupViewHolder;
            groupViewHolder.iv_my_group_msg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showHomeWorkHintDialog(v, finalGroupViewHolder.iv_my_group_msg, "", endTime, "");
                }
            });
        }
    }

    @Override
    public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
        ChildViewHolder childViewHolder = null;
        if (view == null) {
            view = View.inflate(mContext, R.layout.activity_user_dk_list_child, null);
            childViewHolder = new ChildViewHolder();
            childViewHolder.dk_total_day = view.findViewById(R.id.dk_total_day);
            childViewHolder.dk_work_child_name = view.findViewById(R.id.dk_work_child_name);
            childViewHolder.dk_work_dkrule_text = view.findViewById(R.id.dk_work_dkrule_text);
            childViewHolder.dk_zt_obtain = view.findViewById(R.id.dk_zt_obtain);
            childViewHolder.dk_work_btn_area = view.findViewById(R.id.dk_work_btn_area);

            view.setTag(childViewHolder);
        } else {
            childViewHolder = (ChildViewHolder) view.getTag();
        }
        setChildView(i, i1, childViewHolder);
        return view;
    }

    private void setChildView(int i, int i1, ChildViewHolder childViewHolder) {
        if (null != userDkWorks) {
            UserDkWork userDkWork = userDkWorks.get(i);
            childViewHolder.dk_work_child_name.setText(userDkWork.getWorkName());
            String dkRule = userDkWork.getDkRule();
            String[] split = dkRule.split(",");
            StringBuffer sb = new StringBuffer();
            if (split.length == 7) {
                childViewHolder.dk_work_dkrule_text.setText("打卡规则: 每天");
            } else {
                for (int i2 = 0; i2 < split.length; i2++) {
                    String s = split[i2];
                    int indext = Arrays.binarySearch(numberStr, s);
                    if (i2 == split.length - 1) {
                        sb = sb.append(cheStr[indext]);
                    } else {
                        sb = sb.append(cheStr[indext] + ", ");
                    }

                }
                childViewHolder.dk_work_dkrule_text.setText("打卡规则: 周 " + sb.toString());
            }

            if (userDkWork.getIsStart() == 1) {
                childViewHolder.dk_zt_obtain.setText("进行中");
                if (null != userDkWork.getTodayDate()) {
                    childViewHolder.dk_zt_obtain.setTextColor(mContext.getResources().getColor(R.color.color_light_green));
                    int startDkDays = (userDkWork.getTodayDate().getDkDateNum() + 1);
                    String dayText = "已进行" + startDkDays + "/" + userDkWork.getDkdays() + "天";
                    //ForegroundColorSpan 为文字前景色
                    SpannableStringBuilder stringBuilder = new SpannableStringBuilder(dayText);
                    ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.parseColor("#52cc8f"));
                    // 将整数转为字符串
                    String numberString = Integer.toString(startDkDays);
                    int endStr = 3 + numberString.length();
                    stringBuilder.setSpan(redSpan, 3, endStr, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    childViewHolder.dk_total_day.setText(stringBuilder);
                } else {
                    childViewHolder.dk_zt_obtain.setTextColor(mContext.getResources().getColor(R.color.color_light_green));
                    String dayText = "已进行" + 0 + "/" + userDkWork.getDkdays() + "天";
                    //ForegroundColorSpan 为文字前景色
                    SpannableStringBuilder stringBuilder = new SpannableStringBuilder(dayText);
                    ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.parseColor("#52cc8f"));
                    stringBuilder.setSpan(redSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    childViewHolder.dk_total_day.setText(stringBuilder);
                }

            } else if (userDkWork.getIsStart() == 0) {
                childViewHolder.dk_zt_obtain.setText("未开始");
                childViewHolder.dk_zt_obtain.setTextColor(mContext.getResources().getColor(R.color.grade_red));

                String dayText = "已进行" + 0 + "/" + userDkWork.getDkdays() + "天";
                //ForegroundColorSpan 为文字前景色
                SpannableStringBuilder stringBuilder = new SpannableStringBuilder(dayText);
                ForegroundColorSpan yellowSpan = new ForegroundColorSpan(Color.parseColor("#52cc8f"));
                stringBuilder.setSpan(yellowSpan, 3, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                childViewHolder.dk_total_day.setText(stringBuilder);

            } else {
                childViewHolder.dk_zt_obtain.setText("已结束");
                childViewHolder.dk_zt_obtain.setTextColor(mContext.getResources().getColor(R.color.ls_text_color));
                int dkDays = userDkWork.getDkdays();
                String dayText = "已进行" + dkDays + "/" + dkDays + "天";
                SpannableStringBuilder dayTextBuilder = new SpannableStringBuilder(dayText);
                ForegroundColorSpan greenSpan = new ForegroundColorSpan(Color.parseColor("#52cc8f"));
                // 将整数转为字符串
                String numberString = Integer.toString(dkDays);
                int endStr = 3 + numberString.length();
                dayTextBuilder.setSpan(greenSpan, 3, endStr, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                childViewHolder.dk_total_day.setText(dayText);
            }
        }

    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    public void addAll(List<UserDkWork> userDkWorks) {
        if (this.userDkWorks == null) {
            this.userDkWorks = new ArrayList<UserDkWork>();
        }
        if (userDkWorks != null) {
            switch (addType) {
                case ADD_TYPE_ALL:
                    this.userDkWorks.addAll(userDkWorks);
                    break;

                case ADD_TYPE_YES:
                    for (UserDkWork userDkWork : userDkWorks) {
//                        if (epaperInfo.isAdded()) {
                        this.userDkWorks.add(userDkWork);
//                        }
                    }
                    break;

                default:
                    for (UserDkWork userDkWork : userDkWorks) {
//                        if (epaperInfo.isAdded()) {
                        this.userDkWorks.add(userDkWork);
//                        }
                    }
                    break;
            }
            notifyDataSetChanged();
        }
    }

    /**
     * 清空数据
     */
    public void clear() {
        if (userDkWorks != null) {
            userDkWorks.clear();
            //notifyDataSetChanged();
        }
    }

    /**
     * 组视图助手
     */
    private class GroupViewHolder {
        /**
         * 时间
         */
        private TextView mTimeTv;
        /**
         * 进行中
         */
        private ImageView iv_my_work_status_start;
        /**
         * 已结束
         */
        private ImageView iv_my_work_status_finish;

        /**
         * 整个item view句柄,用于当作业撤销时隐藏整个item
         */
        private View item_my_group_parent_view;

        /**
         * 留言按钮
         */
        private ImageView iv_my_group_msg;
    }

    /**
     * 子视图助手
     */
    public static class ChildViewHolder {
        /**
         * 作业内容名称
         */
        public TextView dk_work_child_name;

        public TextView dk_work_dkrule_text;

        public TextView dk_total_day;

        public TextView dk_zt_obtain;

        /**
         * 点击区域
         */
        public ViewGroup dk_work_btn_area;


    }

    /**
     * 显示作业布置信息
     *
     * @param clickView
     * @param iv_my_group_msg
     * @param workName
     * @param endTime
     * @param workMessage
     */
    private void showHomeWorkHintDialog(View clickView, ImageView iv_my_group_msg, String workName, String endTime, String workMessage) {
        View workHintDialogView = LayoutInflater.from(mContext).inflate(R.layout.dialog_dk_work, null);

        final int spotXY[] = new int[2];
        // 获取锚点View在屏幕上的左上角坐标位置
        iv_my_group_msg.getLocationOnScreen(spotXY);
        int spotX = iv_my_group_msg.getWidth();
        int spotY = iv_my_group_msg.getHeight();
        //偏移量 = 屏幕的一半 - 弹窗的一半 - 锚点的一半 - 边距
        int screenWidth = DisplayUtils.getScreenWidth(mContext);
        int screenHeight = DisplayUtils.getScreenHeight(mContext);
        workHintDialogView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int dialogWidth = workHintDialogView.getMeasuredWidth();
        int dialogHeight = workHintDialogView.getMeasuredHeight();
        int offsetX = (screenWidth / 2 - dialogWidth / 2 - (screenWidth - spotXY[0]) + spotX / 2);//右边便宜要加上锚点的一半和右边的边距。
        int offsetY = -(screenHeight / 2 - dialogHeight / 2 - spotXY[1] + DisplayUtils.getStatusBarHeight(mContext) / 2 - spotY) - DisplayUtils.dip2px(mContext, 30);
        CWLog.i("offsetX", +offsetX + "");
        CWLog.i("offsetY", +offsetY + "");
        final DKWorkDialog homeWorkHintDialog = new DKWorkDialog(mContext, workHintDialogView, endTime, offsetX, offsetY, true);
        homeWorkHintDialog.show();
        workHintDialogView.findViewById(R.id.rll_group_head).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                homeWorkHintDialog.dismiss();
            }
        });
    }
}
